$(function(){
    initJstree();

    $("#locationSelect").select2({
        dropdownParent: $('#locationSelectForm'),
        language: {
            "noResults": function () {
                return "没有数据";
            }
        },
        allowClear:true,
        placeholder: "请选择地理位置",
        data:null
    });

    // $.ajax({
    //     type: "GET",
    //     contentType: "application/json",
    //     dataType: "json",
    //     url: "${baseURL}/water/dt_device/getAll2",
    //     async:false,
    //     success:function(data){
    //         if(data.code === 0){
    //             $("#deviceSelect").select2({
    //                 placeholder: "请选择监测主机",
    //                 dropdownParent: $('#sensorSelectForm'),
    //                 language: {
    //                     "noResults": function () {
    //                         return "没有数据";
    //                     }
    //                 },
    //                 allowClear:true,
    //                 data:data.data
    //             });
    //             var device_id = $("#deviceSelect").find("option:selected").val();
    //             $.ajax({
    //                 type: "GET",
    //                 contentType: "application/json",
    //                 dataType: "json",
    //                 url: "${baseURL}/water/dt_sensor/getNameByDeviceId?device_id=" + device_id,
    //                 async:false,
    //                 success: function (data) {
    //                     if(data.code === 0){
    //                         $("#sensorSelect").select2({
    //                             dropdownParent: $('#sensorSelectForm'),
    //                             language: {
    //                                 "noResults": function () {
    //                                     return "没有数据";
    //                                 }
    //                             },
    //                             allowClear:true,
    //                             placeholder: "请选择监测主机",
    //                             data:data.data
    //                         });
    //                     }
    //                 }
    //             });
    //         }
    //     }
    // });
});

$("#locationSelect").change(function () {
    var ID = $("#locationSelect").val();
    $.ajax({
        type: "GET",
        contentType: "application/json",
        dataType: "json",
        url: "${baseURL}/water/dt_geobuilding/getOne?id=" + ID,
        async:false,
        success: function (data) {
            console.log("change");
            console.log(data);
            if(data.code === 0){
                var x_pos = data.data.pos_x;
                var y_pos = data.data.pos_y;
                $("#pos").css({
                    "left":($("#dtMapImg").width()) * x_pos + "px",
                    "top":($("#dtMapImg").height()) * y_pos + "px",
                });
            }
        }
    });

})
function initJstree() {
    $.ajax({
        type: "GET",
        contentType: "application/json",
        dataType: "json",
        url: "${baseURL}/water/dt_geobuilding/getTree",
        async:false,
        success:function (data_in) {
            var jsonObj = data_in;
            var data = [];
            for(var i  in jsonObj.data){
                var level1 = jsonObj.data;
                if(i==0){
                    var level1Obj = {
                        text:level1[i].name,
                        id:level1[i].id,
                        icon:"glyphicon glyphicon-globe",
                        state: {"opened" : true }
                    };
                }else {
                    var level1Obj = {
                        text:level1[i].name,
                        id:level1[i].id,
                        icon:"glyphicon glyphicon-globe",
                        state: {"opened" : false }
                    };
                }
                if(level1[i].children != null)
                {
                    var level2 = level1[i].children;
                    var level2Arr = [];
                    for(var j in level2){
                        if(i==0 && j==0){
                            var level2Obj = {
                                text: level2[j].name,
                                id: level2[j].id,
                                icon: "glyphicon glyphicon-home",
                                state: {"opened" : true }
                            };
                        }else {
                            var level2Obj = {
                                text: level2[j].name,
                                id: level2[j].id,
                                icon: "glyphicon glyphicon-home",
                                state: {"opened" : false }
                            };
                        }
                        if(level2[j].children != null)
                        {
                            var level3 = level2[j].children;
                            var level3Arr = [];
                            for(var k in level3){
                                var level3Obj = {
                                    text: level3[k].name,
                                    id: level3[k].id,
                                    icon: "glyphicon glyphicon-flag"
                                };
                                level3Arr.push(level3Obj);
                            }
                            level2Obj .children = level3Arr;
                        }
                        level2Arr.push(level2Obj);
                    }
                    level1Obj.children = level2Arr;
                }
                data.push(level1Obj);
            }

            $('#jsTreeJSON').data('jstree',false).empty();
            $('#jsTreeJSON').jstree({
                'core' : {
                    'data' : data,
                    'async' : true
                }
            });
        }
    });
    $("#changeBtn").prop("disabled", true);
    $("#deleteBtn").prop("disabled", true);
    $("#mapBtn").prop("disabled", true);
    $("#posBtn").prop("disabled", true);
}

$("#jsTreeJSON").on("select_node.jstree", function (e, data) {
    $("#changeBtn").prop("disabled", false);
    $("#deleteBtn").prop("disabled", false);
    $("#mapBtn").prop("disabled", false);
    var imgUrl = "http://" + getURL() + "${baseURL}/water/file/dt_geobuilding/getMap?id=" + data.node.id;
    $("#titleH5").empty();
    // $("#mapPicture").empty();
    // $("#mapPicture").append(
    //     '<img id="mapImg" width="100%"  src='+ imgUrl + ' style="margin:0;padding: 0" onclick="mapOnClick(event)" />'
    // );
    $("#dtMapImg").attr("src", imgUrl);
    var level = data.node.parents.length;
    if(level == 1){
        $("#pos").css("display","block");
        $.ajax({
            type: "GET",
            contentType: "application/json",
            dataType: "json",
            url: "${baseURL}/water/dt_geobuilding/getBuilding?parent_id=" + data.node.id,
            async:false,
            success: function (data) {
                console.log(data);
                if(data.code === 0){
                    $("#locationSelect").find('option').remove();
                    $("#locationSelect").select2({
                        dropdownParent: $('#locationSelectForm'),
                        language: {
                            "noResults": function () {
                                return "没有数据";
                            }
                        },
                        allowClear:true,
                        placeholder: "请选择地理位置",
                        data:data.data
                    });
                    $("#dtMapImg").load(function () {
                        var x_pos = data.data[0].pos_x;
                        var y_pos = data.data[0].pos_y;
                        var name = data.data[0].text;
                        $("#pos").css({
                            "left":($("#dtMapImg").width()) * x_pos + "px",
                            "top":($("#dtMapImg").height()) * y_pos + "px",
                        });
                        //$("#mapPicture").append('<div id="posimg" class="ip_tooltip ip_img32" style="top:' + (h * y_pos) + "px" + ' ; left:' + (w * x_pos) + "px" + ' ;" data-tooltipbg="bgblack" data-animationtype="btt-slide"  data-round="roundBgW"><p style="text-align: center">'+name+'</p></div>');
                        $("#iPicture").iPicture_base();
                    });

                }
            }
        });
    }
    else if(level == 2){
        $("#pos").css("display","block");
        $.ajax({
            type: "GET",
            contentType: "application/json",
            dataType: "json",
            url: "${baseURL}/water/dt_geobuilding/getFloor?parent_id=" + data.node.id,
            async:false,
            success: function (data) {
                if(data.code === 0){
                    $("#locationSelect").find('option').remove();
                    $("#locationSelect").select2({
                        dropdownParent: $('#locationSelectForm'),
                        language: {
                            "noResults": function () {
                                return "没有数据";
                            }
                        },
                        allowClear:true,
                        placeholder: "请选择地理位置",
                        data:data.data
                    });
                    $("#dtMapImg").load(function () {
                        var x_pos = data.data[0].pos_x;
                        var y_pos = data.data[0].pos_y;
                        var name = data.data[0].text;
                        $("#pos").css({
                            "left":($("#dtMapImg").width()) * x_pos + "px",
                            "top":($("#dtMapImg").height()) * y_pos + "px",
                        });
                        //$("#mapPicture").append('<div id="posimg" class="ip_tooltip ip_img32" style="top:' + (h * y_pos) + "px" + ' ; left:' + (w * x_pos) + "px" + ' ;" data-tooltipbg="bgblack" data-animationtype="btt-slide"  data-round="roundBgW"><p style="text-align: center">'+name+'</p></div>');
                        $("#iPicture").iPicture_base();
                    });

                }
            }
        });
    }
    else{
        $("#pos").css("display","none");
        $("#locationSelect").find('option').remove();
        $("#locationSelect").select2({
            dropdownParent: $('#locationSelectForm'),
            language: {
                "noResults": function () {
                    return "没有数据";
                }
            },
            allowClear:true,
            placeholder: "请选择地理位置",
            data:null
        });
    }
});

$("#areaSave").click(function(){
    var text = $("#areaInput").val();
    if(text != ""){
        $.ajax({
            type: "POST",
            contentType: "application/x-www-form-urlencoded",
            dataType: "json",
            url: "${baseURL}/water/dt_geobuilding/addArea",
            data:{"name":text},
            success:function(data){
                if(data.code === 0){
                    swal({
                        title: "添加成功。",
                        type: "success"
                    },function(isConfirm){
                        if(isConfirm) location.reload();
                    });
                }
                else{
                    swal({
                        title: "数据已存在。",
                        type: "error"
                    })
                }
            },
            error:function(xhr, status, error){
                swal({
                    title: "请求失败。",
                    type: "error"
                })
            }
        });
    }
});

$("#deleteBtn").click(function(){
    var id = $("#jsTreeJSON").jstree("get_selected")[0];
    $.ajax({
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        dataType: "json",
        url: "${baseURL}/water/dt_geobuilding/delete?id=" + id,
        success:function(data){
            if(data.code === 0){
                swal({
                    title: "删除成功。",
                    type: "success"
                },function(isConfirm){
                    if(isConfirm) location.reload();
                });
            }
            else{
                swal({
                    title: "删除失败。",
                    type: "error"
                })
            }
        },
        error:function(xhr, status, error){
            swal({
                title: "请求失败。",
                type: "error"
            })
        }
    });
});

$("#addBuildingBtn").click(function(){
    $.ajax({
        type: "GET",
        contentType: "application/json",
        dataType: "json",
        url: "${baseURL}/water/dt_geobuilding/getArea",
        async:false,
        success: function (data) {
            if(data.code === 0){
                $("#areaSelect").select2({
                    dropdownParent: $('#buildingForm'),
                    language: {
                        "noResults": function () {
                            return "没有数据";
                        }
                    },
                    allowClear:false,
                    placeholder: "请选择区域",
                    data:data.data
                });
            }
        }
    });
});

$("#buildingSave").click(function(){
    var parent_id = $("#areaSelect").find("option:selected").val();
    var text = $("#buildingInput").val();
    if(text != ""){
        $.ajax({
            type: "POST",
            contentType: "application/x-www-form-urlencoded",
            dataType: "json",
            url: "${baseURL}/water/dt_geobuilding/addBuilding",
            data:{"name":text,"parent_id":parent_id},
            success:function(data){
                if(data.code === 0){
                    swal({
                        title: "添加成功。",
                        type: "success"
                    },function(isConfirm){
                        if(isConfirm) location.reload();
                    });
                }
                else{
                    swal({
                        title: "数据已存在。",
                        type: "error"
                    })
                }
            },
            error:function(xhr, status, error){
                swal({
                    title: "请求失败。",
                    type: "error"
                })
            }
        });
    }
});

$("#addFloorBtn").click(function(){
    $.ajax({
        type: "GET",
        contentType: "application/json",
        dataType: "json",
        url: "${baseURL}/water/dt_geobuilding/getArea",
        async:false,
        success: function (data) {
            if(data.code === 0){
                $("#areaSelect2").select2({
                    dropdownParent: $('#floorForm'),
                    language: {
                        "noResults": function () {
                            return "没有数据";
                        }
                    },
                    allowClear:false,
                    placeholder: "请选择区域",
                    data:data.data
                });
            }
        }
    });
    var parent_id = $("#areaSelect2").find("option:selected").val();
    $.ajax({
        type: "GET",
        contentType: "application/json",
        dataType: "json",
        url: "${baseURL}/water/dt_geobuilding/getBuilding?parent_id=" + parent_id,
        async:false,
        success: function (data) {
            if(data.code === 0){
                $("#buildingSelect").select2({
                    dropdownParent: $('#floorForm'),
                    language: {
                        "noResults": function () {
                            return "没有数据";
                        }
                    },
                    allowClear:false,
                    placeholder: "请选择建筑物",
                    data:data.data
                });
            }
        }
    });
});

$("#areaSelect2").on("select2:open change",function(e){
    var parent_id = $("#areaSelect2").find("option:selected").val();
    $("#buildingSelect").empty();
    $.ajax({
        type: "GET",
        contentType: "application/json",
        dataType: "json",
        url: "${baseURL}/water/dt_geobuilding/getBuilding?parent_id=" + parent_id,
        async:false,
        success: function (data) {
            if(data.code === 0){
                $("#buildingSelect").select2({
                    dropdownParent: $('#floorForm'),
                    language: {
                        "noResults": function () {
                            return "没有数据";
                        }
                    },
                    allowClear:false,
                    placeholder: "请选择建筑物",
                    data:data.data
                });
            }
        }
    });
});

$("#floorSave").click(function(){
    var parent_id = $("#buildingSelect").find("option:selected").val();
    var text = $("#floorInput").val();
    if(text != ""){
        $.ajax({
            type: "POST",
            contentType: "application/x-www-form-urlencoded",
            dataType: "json",
            url: "${baseURL}/water/dt_geobuilding/addFloor",
            data:{"name":text,"parent_id":parent_id},
            success:function(data){
                if(data.code === 0){
                    swal({
                        title: "添加成功。",
                        type: "success"
                    },function(isConfirm){
                        if(isConfirm) location.reload();
                    });
                }
                else{
                    swal({
                        title: "数据已存在。",
                        type: "error"
                    })
                }
            },
            error:function(xhr, status, error){
                swal({
                    title: "请求失败。",
                    type: "error"
                })
            }
        });
    }
});

$("#mapBtn").click(function(){
    var id = $("#jsTreeJSON").jstree("get_selected")[0];
    $("#mapInput").val(id);
});

$("#mapSave").click(function(){
    var form = new FormData(document.forms.namedItem("mapForm"));
    var values = document.getElementById("mapFileInput").value;
    if(values != ""){
        $.ajax({
            url: "${baseURL}/water/dt_geobuilding/mapUpload",
            contentType: false,
            cache: false,
            processData: false,
            type: 'POST',
            dataType: 'json',
            data: form,
            success:function(data){
                if(data.code === 0) {
                    swal({
                        title: "操作成功",
                        type: "success"
                    },function(isConfirm){
                        if(isConfirm) location.reload();
                    });
                }
            },
            error:function(error) {
                swal({
                    title: "提交失败，请检查输入的内容。",
                    type: "error"
                })
            }
        });
    }else {
        swal({
            title: "提交失败，请检查输入的内容。",
            type: "error"
        })
    }

});

$("#changeSave").click(function(){
    var id = $("#jsTreeJSON").jstree("get_selected")[0];
    var text = $("#changeInput").val();
    if(text != ""){
        $.ajax({
            type: "POST",
            contentType: "application/x-www-form-urlencoded",
            dataType: "json",
            url: "${baseURL}/water/dt_geobuilding/updateName",
            data:{"name":text,"id":id},
            success:function(data){
                if(data.code === 0){
                    swal({
                        title: "修改成功。",
                        type: "success"
                    },function(isConfirm){
                        if(isConfirm) location.reload();
                    });
                }
                else{
                    swal({
                        title: "修改失败。",
                        type: "error"
                    })
                }
            },
            error:function(xhr, status, error){
                swal({
                    title: "请求失败。",
                    type: "error"
                })
            }
        });
    }
});

function mapOnClick(e){
    e = e || window.event;
    var imgId ='#'+ $(e.target).attr('id');
    var currentWidth = $(imgId).width();
    var currentHeight = $(imgId).height();
    var offsetX = e.pageX - $(imgId).offset().left;
    var offsetY = e.pageY - $(imgId).offset().top;
    var x = offsetX / currentWidth;
    var y = offsetY / currentHeight;

    $("#xInput").val(x);
    $("#yInput").val(y);
    $("#pos").css({
        "left":($("#dtMapImg").width()) * x + "px",
        "top":($("#dtMapImg").height()) * y + "px",
    });
    // $("#posPNG").remove();
    // $("#posimg").remove();
    // $("#mapPicture").append(
    //     '<img id="posPNG" src="assets/pos.png" width="30px" height="30px;" style="z-index: 1;position: absolute; left: 0;top: 0;"  />'
    // );
    // var left = x * currentWidth + "px";
    // var top = y * currentHeight - 30 + "px";
    // $("#posPNG").css({"left":left,"top":top});
    // $("#posBtn").prop("disabled", false);
};

// $(window).resize(function(){
//     if($("#xInput").val() != ""){
//         $("#posPNG").remove();
//         $("#mapPicture").append(
//             '<img id="posPNG" src="assets/pos.png" width="30px" height="30px;" style="z-index: 1;position: absolute; left: 0;top: 0;"  />'
//         );
//         var x = $("#xInput").val();
//         var y = $("#yInput").val();
//         var currentWidth = $("#mapImg").width();
//         var currentHeight = $("#mapImg").height();
//         var left = x * currentWidth + "px";
//         var top = y * currentHeight - 30 + "px";
//         $("#posPNG").css({"left":left,"top":top});
//     }
// });

$("#locationPosBtn").click(function(){
    var x = $("#xInput").val();
    var y = $("#yInput").val();
    var id =  parseInt($("#locationSelect").find("option:selected").val());
    var formData = new FormData();
    formData.append("id",id);
    formData.append("pos_x",x);
    formData.append("pos_y",y);
    if(x == "" || y == "" ||  id == ""){
        swal({
            title: "请点选坐标和输入数据。",
            type: "error"
        });
    }else{
        $.ajax({
            type: "POST",
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            url: "${baseURL}/water/dt_geobuilding/xyUpload",
            async: false,
            data:formData,
            success:function(data){
                if(data.code === 0){
                    swal({
                        title: "修改成功。",
                        type: "success"
                    },function(isConfirm){
                        if(isConfirm) location.reload();
                    });
                }
                else{
                    swal({
                        title: "修改失败,地理信息是否异常？",
                        type: "error"
                    })
                }
            },
            error:function(xhr, status, error){
                console.log(xhr.responseText)
                swal({
                    title: "请求失败。",
                    type: "error"
                })
            }
        });
    }
});

$("button.btnFlag").click(function(){
    $("#posPNG").remove();
    console.log("remove")
});